<?php
class Empeval_LpImport_EmployeeImport_Users {
	
	/**
	 * Tablica obiektów EmpevalUsers gdzie klucz to ExtId (LogoId z bazy LP)
	 * @var EmpevalUsers[]
	 */
	private $_map = array();
	
	public function __construct() {
		$users = EmpevalUsersQuery::create()
			->useUserRolesRelatedByToUserIdQuery(null, Criteria::LEFT_JOIN)
				->leftJoinRoles()
				->addJoinCondition('Roles', 'Roles.Type = ?', EmpevalRoles::TYPE_RANK)
			->endUse()
			->leftJoinUserPositions()
			->with('UserPositions')
			->with('UserRolesRelatedByToUserId')
			->find();
			//->getArrayCopy('ExtId');
		foreach ($users as $user) {
			$this->_map[$user->getExtId()] = $user;
		}
	}
	
	/**
	 * @param LpEmployees $lpEmployee
	 * @return EmpevalUsers
	 */
	private function _add(LpEmployees $lpEmployee) {
		$extId = $lpEmployee->getLogoId();
		$user = new EmpevalUsers();
		$user->setExtId($extId);
		$user->setActive(true);
		$this->_map[$extId] = $user;
		return $user;
	}
	
	/**
	 * @param LpEmployees $lpEmployee
	 * @return EmpevalUsers
	 */
	private function _getWithAdd(LpEmployees $lpEmployee) {
		$user = $this->get($lpEmployee->getLogoId());
		if (!($user instanceof EmpevalUsers))
			$user = $this->_add($lpEmployee);
		return $user;
	}
	
	/**
	 * @param string $extId
	 * @return EmpevalUsers|NULL
	 */
	public function get($extId) {
		if (key_exists($extId, $this->_map))
			return $this->_map[$extId];
		return null;
	}
	
	/**
	 * @param LpEmployees $lpEmployee
	 * @return EmpevalUsers
	 */
	public function update(LpEmployees $lpEmployee) {
		$user = $this->_getWithAdd($lpEmployee);
		$user->setFname($lpEmployee->getFname());
		$user->setLname($lpEmployee->getLname());
		$user->setEmail($lpEmployee->getEmployeesPositions()->getEmail());
		return $user;
	}
	
}